import { PermissionState } from '@/types/store/permission';
import { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { constantRoutes } from '@/router';
import { listRoutes } from '@/api/system/menu';

const modules = import.meta.glob('../../views/**/**.vue')

export const Layout = () => import('@/layout/index.vue');

const hasPermission = (roles:string[],route:RouteRecordRaw)=>{
  if(route.meta&&route.meta.roles){
    if(roles.includes('ROOT')){
      return true
    }

    return roles.some((role)=>{
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role);
      }
    })

    return false
  }
}

export const filterAsyncRoutes = (routes:RouteRecordRaw[],roles:string[]) =>{
  const res:RouteRecordRaw[] = []
  routes.forEach((route)=>{
    const temp = {...route} as any
    if(hasPermission(roles,temp)){
      if(temp.component =='/layout'){
        temp.component = Layout
      }else{
        const component = modules[`../../views/${temp.component}.vue`] as any;
        if (component) {
          temp.component = modules[`../../views/${temp.component}.vue`];
        } else {
          temp.component = modules[`../../views/error-page/404.vue`];
        }
      }
      if (temp.children) {
        temp.children = filterAsyncRoutes(temp.children, roles);
        temp.component = Layout
      }
      res.push(temp)
     
    }
  })
  return res
}


const usePermissionStore = defineStore({    
  id:'permission',
  state:():PermissionState=>({
    routes: [],
    addRoutes: [],
  }),
  actions:{
    setRoutes(routes:RouteRecordRaw[]){
      this.addRoutes = routes
      this.routes = constantRoutes.concat(routes)
      console.log(this.routes);
      
    },
    generateRoutes(roles:string[]){
      return new Promise((resolve,reject)=>{
        listRoutes().then(res=>{
          const asyncRoutes = res.data.data
          
          const accessedRoutes:any = filterAsyncRoutes(asyncRoutes,roles)
          
          this.setRoutes(accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    }
  }
})

export default usePermissionStore